import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_rtk/common/config.dart';
import 'package:flutter_rtk/entities/banner_entity.dart';
import 'package:flutter_rtk/entities/collection_tools_page_entity.dart';
import 'package:flutter_rtk/entities/current_project_entity.dart';
import 'package:flutter_rtk/entities/login_entity.dart';
import 'package:flutter_rtk/entities/message_page_entity.dart';
import 'package:flutter_rtk/entities/offline_package_entity.dart';
import 'package:flutter_rtk/entities/project_entity.dart';
import 'package:flutter_rtk/entities/tools_entity.dart';
import 'package:flutter_rtk/entities/undo_page_entity.dart';
import 'package:flutter_rtk/entities/user_entity.dart';
import 'package:flutter_rtk/utils/md5_utils.dart';
import 'package:flutter_rtk/utils/request_utils.dart';

class AppApi {
  /// 登陆
  static Future<LoginEntity> login({required String username, required String password}) async {
    var result = await RequestUtils.post(url: "/api/sinoma-auth/oauth/token", params: {
      "tenantId": AppConfig.defaultTenantId,
      "grant_type": "password",
      "scope": "all",
      "type": "account",
      "username": username,
      "password": MD5Utils.toMD5(password),
    });
    return LoginEntity.fromJson(result);
  }

  /// 扫码登陆
  static Future<String> scanLogin({required String scene}) async {
    return await RequestUtils.post(url: "/api/sinoma-portal/authorization/getXcxCode", params: {"scene": scene});
  }

  /// 扫码检测
  static Future<Map<String, dynamic>> scanStatus({required String scene}) async {
    return await RequestUtils.post(url: "/api/sinoma-portal/authorization/sceneLogin", params: {"scene": scene});
  }

  /// 获取用户信息
  static Future<UserEntity> getUserInfo() async {
    var result = await RequestUtils.get(url: "/api/sinoma-user/info");
    return UserEntity.fromJson(result);
  }

  /// 获取首页轮播图
  static Future<BannerEntity> getSwiperInfo({String adType = "1001", int current = 1, int size = 20}) async {
    var result = await RequestUtils.get(url: "/api/sinoma-system/adInfo/page", params: {"adType": adType, "current": current, "size": size});
    return BannerEntity.fromJson(result);
  }

  /// 获取所有项目列表
  static Future<List<ProjectEntity>> getAllProjects() async {
    List<dynamic> results = await RequestUtils.get(url: "/api/sinoma-maindata/project/projectVolumeUp");
    return results.map((e) => ProjectEntity.fromJson(e)).toList();
  }

  /// 获取当前项目
  static Future<CurrentProjectEntity?> getCurrentProject() async {
    var result = await RequestUtils.get(url: "/api/sinoma-system/project/userProject");
    if (result == null || "" == result) {
      return null;
    }
    return CurrentProjectEntity.fromJson(result);
  }

  /// 获取常用工具
  static Future<CollectionToolsPageEntity> getCommonTools({required String projectId, required String projectCode, int current = 1, int size = 9999}) async {
    var result = await RequestUtils.get(url: "/api/sinoma-system/appshortcutMenu/page", params: {"projectId": projectId, "projectCode": projectCode, "current": current, "size": size});
    return CollectionToolsPageEntity.fromJson(result);
  }

  /// 获取所有工具
  static Future<List<ToolsEntity>> getAllTools({required String projectId, required String projectCode, String? deptCode, int current = 1, int size = 9999}) async {
    Map<String, dynamic> result = await RequestUtils.get(url: "/api/sinoma-system/menu/appMenuRoutes", params: {"platform": 3, "projectId": projectId, "projectCode": projectCode, "current": current, "size": size});
    List<dynamic> menuList = result['menuList'] ?? [];
    return menuList.map((e) => ToolsEntity.fromJson(e)).toList();
  }

  /// 获取消息列表
  static Future<MessagePageEntity> getMessagePage({int current = 1, int size = 20, int? isRead}) async {
    Map<String, dynamic> result = await RequestUtils.get(url: "/api/sinoma-message/msgSendDetail/selectMsgByUserId", params: {"current": current, "size": size, "isRead": isRead});
    return MessagePageEntity.fromJson(result);
  }

  /// 消息详情
  static Future<MessageInfo> getMessageDetail({required String msgId}) async {
    Map<String, dynamic> result = await RequestUtils.get(url: "/api/sinoma-message/msgSendDetail/selectParams", params: {"msgId": msgId});
    return MessageInfo.fromJson(result);
  }

  /// 消息状态 -> 已读
  static Future<void> readMessage({required String msgId}) async {
    await RequestUtils.get(url: "/api/sinoma-message/msgSendDetail/readByMsgId", params: {"msgId": msgId});
    return Future(() => true);
  }

  /// 获取待办\已处理\我发起的列表
  static Future<UndoPageEntity> getUndoPage({int current = 1, int size = 20, required String action}) async {
    Map<String, dynamic> result = await RequestUtils.get(url: "/api/sinoma-system/sys/$action", params: {"current": current, "size": size});
    return UndoPageEntity.fromJson(result);
  }

  /// 收藏工具
  static Future<bool> addCollectionTools({List? tools}) async {
    await RequestUtils.post(url: "/api/sinoma-system/appshortcutMenu/submit", data: jsonEncode(tools ?? []));
    return Future(() => true);
  }

  /// 上传
  static Future<dynamic> uploadFile({required String path}) async {
    MultipartFile multipartFile = await MultipartFile.fromFile(path);
    return await RequestUtils.upload(url: "/api/sinoma-srtk/common/fileUpload", data: multipartFile);
  }

  /// 下载文件
  static Future<dynamic> downloadFile({required String url, required String savePath, Function? onReceiveProgress}) async {
    return RequestUtils.download(url: url, savePath: savePath, onReceiveProgress: onReceiveProgress);
  }

  // ------------------------------------ 离线接口 ------------------------------------

  /// 获取最新版本包
  /// packageType = 1 ==》 apk/ipa or zip
  /// platformType => Android or iOS
  /// applyType => zip
  static Future<OfflinePackageEntity> fetchLatestOfflinePackage({required int packageType, String platformType = "", String applyType = ""}) async {
    String checkUrl = "/api/sinoma-maindata/offline-package/getTopVersionInfo";
    Map params = {"packageType": packageType};
    if (platformType.isNotEmpty) {
      params['platformType'] = platformType;
    }
    if (applyType.isNotEmpty) {
      params['applyType'] = applyType;
    }
    Map<String, dynamic> result = await RequestUtils.post(url: checkUrl, data: jsonEncode(params));
    return OfflinePackageEntity.fromJson(result);
  }

  /// 配置下发
  static Future<dynamic> fetchConfigList() async {
    return await RequestUtils.post(url: "/api/sinoma-maindata/offline-download/getList", data: jsonEncode({}));
  }

  /// 执行二级接口
  static Future<dynamic> invokeUrl({required String url, int? timeout}) async {
    return RequestUtils.get(url: url, timeout: timeout);
  }

  /// 数据同步
  static Future<dynamic> syncOfflineData({required List<Map<String,dynamic>> data}) async {
    return await RequestUtils.post(url: "/api/sinoma-maindata/offline-download/asyncData", data: jsonEncode({"asyncDataList": data}));
  }
}
